import {
  HttpApi
} from '../../../model/index.js'
const httpApi = new HttpApi
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		hasTake: false,
		tempFilePath:""
	},

	takePhoto() {
		var _this = this
		const ctx = wx.createCameraContext()
		ctx.takePhoto({
			quality: 'low',
			success: (res) => {
				this.setData({
					src:res.tempImagePath,	
					tempFilePath: res.tempImagePath,
					hasTake: true,
				}) 
			}
		})
	},
	error(e) {
		console.log(e.detail)
	},
	reTake() {
		this.setData({
			hasTake: false,
		})
	},
	
	submit() {
		// wx.navigateBack({})
    var login = wx.getStorageSync('login')
    
		wx.showLoading({
			title: '正在上传...',
			mask: true
		})
		console.log("上传的图片:",this.data.tempFilePath)
		this.uploadimg({
			url: 'https://m.zhiliaoyuedu.cn/pic/upload', //这里是你图片上传的接口
			path: [this.data.tempFilePath] //这里是选取的图片的地址数组
		});
	},
	
	uploadimg(data) {
   
		var _this = this,
			i = data.i ? data.i : 0, 
			success = data.success ? data.success : 0, 
			fail = data.fail ? data.fail : 0; 
		var uploadUrls = [];
		var token = wx.getStorageSync('token')
		wx.uploadFile({			
			url: data.url,
			filePath: data.path[i],
			name: 'file', 			
			header: {
				'Authorization': token,
				'content-type':'multipart/form-data'
			},
			formData: {
				
			}, 
			success: (res) => {
				var resData = JSON.parse(res.data)
				console.log("upload resData:",resData)
				success++; 				
				uploadUrls = uploadUrls.concat(resData.data)			
			},
			fail: (res) => {
				fail++; //图片上传失败，图片上传失败的变量+1
				console.log('fail:' + i + "fail:" + fail);
			},
			complete: () => {
				console.log(i);
				i++; //这个图片执行完上传后，开始上传下一张
				if (i == data.path.length) { //当图片传完时，停止调用          		
					console.log("postData:",uploadUrls)
					if(uploadUrls.length > 0){
						httpApi.addPack(uploadUrls[0]).then(res => {
							console.log("addPack:", res.data)
							if(res.code == 0){
								wx.hideLoading()
								wx.showToast({
										title: res.msg
								})
								wx.reLaunch({
                  url: "../../home"
								})
							}
						})
					}
				} else { //若图片还没有传完，则继续调用函数
					console.log(i);
					data.i = i;
					data.success = success;
					data.fail = fail;
					_this.uploadimg(data);
				}
	
			}
		});
	}
})
